package main

import (
	"awesomeProject/zinx"
	"fmt"
	"io"
	"math/rand"
	"net"
	"time"
)

func main() {
	fmt.Println("client start ...")
	time.Sleep(1 * time.Second)
	conn,err := net.Dial("tcp","127.0.0.1:8999")
	if err !=nil {
		fmt.Println("client start err,exit!")
		return
	}
	for {
		rand.Seed(time.Now().UnixNano())
		msgId := rand.Intn(2)
		fmt.Println("msgid:",msgId)
		dp := zinx.NewDataPack()
		binaryMsg,err := dp.Pack(zinx.NewMsgPackage(uint32(msgId),[]byte("我是客户端")))
		if err !=nil {
			fmt.Println("msg pack err",err)
			return
		}

		if _,err := conn.Write(binaryMsg);err != nil {
			fmt.Println("write binarymsg err",err)
			return
		}

		binaryHead := make([]byte,dp.GetHeadLen())
		if _,err:= io.ReadFull(conn,binaryHead);err !=nil {
			fmt.Println("read binaryHead err",err)
			break
		}
		msgHead,err :=dp.Unpack(binaryHead)
		if err != nil {
			fmt.Println("unpack binaryhead err",err)
			break
		}
		if msgHead.GetMsgLen() > 0 {
			msg := msgHead.(*zinx.Message)
			msg.Data = make([]byte,msgHead.GetMsgLen())
			if _,err := io.ReadFull(conn,msg.Data);err!=nil{
				fmt.Println("read msg error",err)
				break
			}
			fmt.Printf("-->Recv Server Msg Id:%d;len:%d,data:%s \n",msg.Id,msg.DataLen,msg.Data)
		}



		time.Sleep(3 * time.Second)
	}


}
